package com.qp.basics.common.config.estivate;

import com.alibaba.druid.pool.DruidDataSource;
import com.qp.basics.common.datasource.DynamicDataSource;
import com.qp.basics.common.datasource.DynamicDataSourceContextHolder;
import com.qp.basics.estivate.Database;
import com.qp.basics.estivate.jdbc.core.EstivateTemplate;
import com.qp.basics.estivate.mysql.DatabaseMySql;
import com.qp.basics.estivate.support.DataSourceConnectionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class EstivateConfig
{

    @Autowired
    DataSource dataSource;
    @Autowired
    DataSource masterDataSource;

    @Bean("et")
    public EstivateTemplate et()
    {
        return new EstivateTemplate(null){
            private Map<String, Database> m = new HashMap<>();
            @Override
            public Database getDatabase() {
                String domain = DynamicDataSourceContextHolder.getDataSourceType();
                Database database = m.get(domain);
                if(database == null){
                    DynamicDataSource ds = (DynamicDataSource)dataSource;
                    DataSourceConnectionProvider connectionProvider= new DataSourceConnectionProvider(ds);
                    database = new DatabaseMySql();
                    database.setConnectionProvider(connectionProvider);
                    database.setTableSchema(ds.getDbname(domain));
                    m.put(domain,database);
                }
                return database;
            }
        };
    }

    @Bean("etMaster")
    public EstivateTemplate etMaster()
    {
        return new EstivateTemplate(null){
            private Map<String, Database> m = new HashMap<>();
            @Override
            public Database getDatabase() {
                String domain = "master";
                Database database = m.get(domain);
                if(database == null){
                    DruidDataSource ds = (DruidDataSource)masterDataSource;
                    DataSourceConnectionProvider connectionProvider= new DataSourceConnectionProvider(ds);
                    database = new DatabaseMySql();
                    database.setConnectionProvider(connectionProvider);
                    String url = ds.getUrl();
                    int qmarkIndex = url.indexOf("?");
                    int slashIndex = url.substring(0,qmarkIndex).lastIndexOf("/");
                    String schema = url.substring(slashIndex+1,qmarkIndex);
                    database.setTableSchema(schema);
                    m.put(domain,database);
                }
                return database;
            }
        };
    }
}
